package com.yj.springbootmybatis.util;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Slf4j
public class CookieUtils {
    public static void clearCookieInfo(String userId,HttpServletRequest req,HttpServletResponse resp) {

        Cookie[] cookies = req.getCookies();
        log.info("clearCookieInfo() => cookies:{}",cookies.toString());
        for (Cookie cookie : cookies) {
            log.info("clearCookieInfo() => cookie:{},{}",cookie.getName(),cookie.getPath());
            if(userId.equals(cookie.getName())){
                cookie.setPath("/");
                cookie.setMaxAge(0);
                resp.addCookie(cookie);
            };
        }

    }


    public static void addCookieInfo(String key, String value, HttpServletRequest req, HttpServletResponse resp){

        try {
            String encode = URLEncoder.encode(value, "UTF-8");
            Cookie cookie = new Cookie(key,encode);
            cookie.setMaxAge(60*60*12);
            cookie.setPath("/");
            resp.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }
}
